import {
    type TranscodeRequest,
    type TranscodeResponse,
    type TranscodeStreamResponse,
    type RunResponse,
    type RunRequest,
    type updateRequest,
    type updateResponse
} from "@/types";

import FetchStream from "@/tools/FetchStream";

const env = import.meta.env;
let API = env.VITE_API_URL;

// if (env.MODE === 'rustedu') {
//     // 新服务器：47.122.25.236
//     // 用于实验新功能
//     API = "https://api.rustedu.com";
// } else if (env.MODE === 'c2rust') {
//      // 之前的服务器：123.56.139.59
//      // 页面部署在github，域名为https://c2rust.cn/
//     API = "https://dev.opencamp.cn/c2rust";
// }

console.log(import.meta.env);


export const transcode = async (data: TranscodeRequest): Promise<TranscodeResponse> => {
    const response = await fetch(API + '/api/transcode', {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
    });
    return await response.json();
}

function stream(url: string, data: TranscodeRequest, onmessage: (response: TranscodeStreamResponse) => void, ondone: () => void ) {
    new FetchStream({
        url: API + '/api/transcode/stream',
        requestInit: { // fetch 配置项
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Accept": "text/event-stream",
            },
            body: JSON.stringify(data),
        },
        onmessage: (dataList: string[], index: number) => {
            for (const item of dataList) {
                
                if (item !== '[DONE]') {
                    try {
                        const data_json = JSON.parse(item);
                        onmessage(data_json);
                    } catch(_) {
                        // 将解析错误的内容返回缓存，在下一次消息中添加到新消息的头部
                        return item;
                    }
                }
            }
            return '';
        },
        ondone: () => {
            // console.log('done!', content);
            ondone();
        },
        ontimeout: () => {
            console.log('timeout!');
        }
    });
}

export function transcode_stream(data: TranscodeRequest, onmessage: (response: TranscodeStreamResponse) => void, ondone: () => void ){
    stream('/api/transcode/stream', data, onmessage, ondone);
}

export const run = async (data: RunRequest): Promise<RunResponse> => {
    const response = await fetch(API + '/api/run', {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
    });
    return await response.json();
}

export const update = async (data: updateRequest): Promise<updateResponse> => {
    const response = await fetch(API + '/api/transcode/update', {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
    });
    return await response.json();
}

export const auto_transcode = async (data: TranscodeRequest): Promise<TranscodeResponse> => {
    const response = await fetch(API + '/api/transcode/auto', {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
    });
    return await response.json();
}

// export default {
    // transcode: async (data: TranscodeRequest): Promise<TranscodeResponse> => {
    //     const response = await fetch(API + '/api/transcode', {
    //         method: "POST",
    //         headers: {
    //           "Content-Type": "application/json",
    //         },
    //         body: JSON.stringify(data),
    //     });
    //     return await response.json();
    // },
    // run: async (data) => {
    //     const response = await fetch(API + '/api/run', {
    //         method: "POST",
    //         headers: {
    //           "Content-Type": "application/json",
    //         },
    //         body: JSON.stringify(data),
    //     });
    //     return await response.json();
    // }
// }